package com.bgt.springboot.first.controller;

import com.bgt.springboot.first.repository.UserPageRepository;
import com.bgt.springboot.first.repository.UserRepository;
import com.bgt.springboot.first.service.UserService;
import com.bgt.springboot.first.vo.DemoVo;
import com.bgt.springboot.first.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * Created by bgt on 2017/4/16.
 * http://projects.spring.io/spring-boot/
 */
@RestController
public class FirstController {
    @Autowired
    private UserService userService;
    @RequestMapping("/hello")
    public String first() {
        return "hello";
    }

    /**
     * 默认SpringBoot使用的json框架是jackjson
     * @return
     */
    @RequestMapping("/getdemo")
    public DemoVo getdemo() {
        DemoVo demoVo=new DemoVo();
        demoVo.setAge(10);
        demoVo.setName("bgt");
        return demoVo;
    }
    /**
     * 默认SpringBoot使用的json框架是jackjson
     * @return
     */
    @RequestMapping("/adduser")
    public List<User> adduser() {
        User user=new User();
        user.setAge(101);
        userService.add(user);
        // List<User> users= userService.findById(1);
         List<User> users2= userService.findById2(1);
        return users2;
    }
    @Autowired
    private com.bgt.springboot.first.repository.UserPageRepository userPageRepository;

    /**
     *
     * @param age
     * @param page
     * @param size
     * @return
     * 结果集
     * {"content":[{"id":1,"age":100}],"last":true,"totalElements":1,"totalPages":1,"size":15,"number":0,"sort":[{"direction":"DESC","property":"id","ignoreCase":false,"nullHandling":"NATIVE","ascending":false,"descending":true}],"first":true,"numberOfElements":1}
     */
    @RequestMapping(value = "/params", method= RequestMethod.GET)
    @ResponseBody
    public Page<User> getEntryByParams(@RequestParam(value = "age", defaultValue = "100") Integer age, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "15") Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<User> pages=userPageRepository.findByAge(age,pageable);
        Iterator<User> it=pages.iterator();
        while(it.hasNext()){
            System.out.println("value:"+((User)it.next()).getId());
        }
        return pages;
    }
    public static void main(String[] args) {
        SpringApplication.run(FirstController.class);
        System.out.println("启动成功");
    }
}
